package cn.ggsaas.base.serializer;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import cn.ggsaas.base.enums.IEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Json序列化枚举类型
 *
 * @author liyuzhen
 * @date 2019/9/24 11:35 上午
 */
@Slf4j
public class JsonValueSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeNumber(value);
        JsonStreamContext outputContext = gen.getOutputContext();
        String currentName = outputContext.getCurrentName();

        Object currentValue = outputContext.getCurrentValue();
        try {
            Field field = currentValue.getClass().getDeclaredField(currentName);
            JsonValue annotation = field.getAnnotation(JsonValue.class);
            if (annotation != null) {
                Class<?> enumClass = annotation.value();
                if (enumClass.isEnum()) {
                    String jsonKey = annotation.key();
                    String key = currentName + "Value";
                    if (StrUtil.isNotBlank(jsonKey)) {
                        key = jsonKey;
                    }
                    String enumValue = null;
                    Object[] enumConstants = enumClass.getEnumConstants();
                    if (enumConstants != null) {
                        for (Object enumConstant : enumConstants) {
                            IEnum iEnum = (IEnum) enumConstant;
                            int code = iEnum.getCode();
                            if (value.equals(code)) {
                                enumValue = iEnum.getValue();
                                break;
                            }
                        }
                    }
                    gen.writeFieldName(key);
                    gen.writeRawValue(enumValue);
                }
            }
        } catch (NoSuchFieldException e) {
            log.error(e.getMessage(), e);
        }


    }
}
